<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import GlobalStyle from './components/style/GlobalStyle.vue'
import AuthStyle from './components/style/AuthStyle.vue'
import TodoStyle from './components/style/TodoStyle.vue'

const router = useRouter()

const currentUserName = ref('')
const errorMsg = ref('')
const users = ref<{ username: string; password: string; createdAt: number }[]>([])

const loadUsers = (): { username: string; password: string; createdAt: number }[] => {
  try {
    const raw = localStorage.getItem('todo_users')
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}
const saveUsers = () => localStorage.setItem('todo_users', JSON.stringify(users.value))

const clearError = () => {
  if (errorMsg.value) {
    errorMsg.value = ''
    document.querySelector('.error-msg')?.classList.remove('success-msg')
  }
}

const handleLoginSuccess = (username: string) => {
  localStorage.setItem('todo_currentUser', username)
  currentUserName.value = username
  router.push('/todo')  
}

const handleAddUser = (user: { username: string; password: string; createdAt: number }) => {
  users.value.push(user)
  saveUsers()
}

const handleSetError = (msg: string, isSuccess = false) => {
  errorMsg.value = msg
  const el = document.querySelector('.error-msg')
  if (el) {
    if (isSuccess) el.classList.add('success-msg')
    else el.classList.remove('success-msg')
  }
}

onMounted(() => {
  users.value = loadUsers()
  const storedUser = localStorage.getItem('todo_currentUser')
  if (storedUser) {
    currentUserName.value = storedUser
    if (router.currentRoute.value.path === '/login') {
      router.push('/todo')
    }
  }
})
</script>

<template>
  <GlobalStyle />
  <AuthStyle />
  <TodoStyle />

  <div class="top-bar">
    仓库地址：<a href="https://gitee.com/group-assignment_4/vue-group" target="_blank">https://gitee.com/group-assignment_4/vue-group</a>
  </div>
  
  <div class="fullscreen-hand-drawn">
    <!-- 登录/注册页面背景装饰 -->
    <div class="bg-decoration" v-if="$route.name === 'login' || $route.name === 'register'">
      <div class="dot"></div>
      <div class="dot"></div>
      <div class="dot"></div>
      <div class="line"></div>
      <div class="line"></div>
    </div>

    <!-- 路由视图-->
    <router-view 
      :users="users"
      :error-msg="errorMsg"
      @loginSuccess="handleLoginSuccess"
      @registerSuccess="router.push('/login')"
      @toRegister="router.push('/register')"
      @toLogin="router.push('/login')"
      @clearError="clearError"
      @setError="handleSetError"
      @addUser="handleAddUser"
    />
  </div>
</template>